import {replaceByObj} from "./xUtil.js";

/**
 *
 * cfg {el,data :jdCatalog , style : class , }
 * data :[{code,name,icon,link}]
 */
export default class xCatalog {
    /* 定义变量 开始*/
    $root ;
    $main;
    $point;
    $activeItem;
    vJdCatalog ;

    vDoing = false;
    vTmplBase = `<div class="{{class}}" data-key="catalog-cntr" >
                      <div data-key="title"><span>目录</span></div>
                      <div data-key="main"></div>
                 </div> `;

    vTmplItem =`<a href="#{{link}}" data-key="item" data-code="{{code}}">
                    <i class="iconfont icon-dot"></i>
                    <span>{{name}}</span>
                </a>`;

    /*定义变量 结束*/
    // 构造函数
    constructor(cfg) {
        this.$root = $('#' + cfg.el);
        this.vJdCatalog = cfg.data;
        this.$root.html(this.vTmplBase.replace('{{class}}', !cfg.style ? 'catalog-style-1' : cfg.style));
        this.renderInit();
    };

    renderInit(){
        this.$main = this.$root.find('[data-key="main"]');
        this.$point =this.$root.find('[data-key="point"]');
        this.$main.html(this.renderItem());
        this.$root.on('click', '[data-key="item"]', this.evActiveItem.bind(this));

        document.querySelector('body').onscroll = this.evScroll.bind(this);
        //第一个激活
        this.activeItem(this.vJdCatalog[0].code);

    }
    
    renderItem(){
        let items = '';
        for(let i=0;i<this.vJdCatalog.length;i++)
            items += replaceByObj(this.vTmplItem,this.vJdCatalog[i]);
        return items;
    }

    activeItem(code){
        //设置 point 位置
        let $target = this.$main.find('[data-code="'+code+'"]');
        if(this.$activeItem) {
            this.$activeItem.removeClass('active');
        }
        this.$activeItem = $target;
        this.$activeItem.addClass('active');
    };

    evActiveItem(e){
        // 去掉滚动 防止 重复 操作
        document.querySelector('body').onscroll = null;
        let code = e.currentTarget.getAttribute("data-code");
        this.activeItem(code);
        //激活滚动
        document.querySelector('body').onscroll = this.evScroll.bind(this);
    }

    evScroll(){
        //点击滚动事件触发的，非处理状态则处理
        if(!this.vDoing){
            this.vDoing= true;
            setTimeout(this.scrollDo.bind(this),50);
        }
    }

    scrollDo(){
        let docHeight = document.documentElement.clientHeight || window.innerHeight;
        let index=-1;
        for(let i=0;i<this.vJdCatalog.length;i++){
            if(document.getElementById(this.vJdCatalog[i].link).getBoundingClientRect().top>docHeight ){
                index = i-1;
                break;
            }
            if(i==this.vJdCatalog.length-1)
                index = i;
        }
        //刷新
        if(index>-1)
            this.activeItem(this.vJdCatalog[index].code);
        //处理完 归位
        this.vDoing = false;
    }
}